package com.mantru.iotpot.setting;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.datepicker.MaterialDatePicker;
import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.DateClass.ErrorData;
import com.mantru.iotpot.DateClass.ResponseData;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Util.ToastUtils;
import com.mantru.iotpot.setting.Adapter.FaultLogAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class FaultLogActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout back;
    private EditText number;
    private TextView date;
    private RecyclerView recyclerView;
    private ImageView clean;
    private ApplicationClass ac;
    private String TAG = "FaultLogActivity";
    private List<ErrorData> errorDataList = new ArrayList<>();
    private boolean success;
    private int pageIndex = 1;//当前页数
    private int pageCount;//总页数
    private int limit = 10;//每页显示行数
    private int recordCount;//数据总数
    private int dataSize;
    private ImageView search;
    private Button left;
    private Button right;
    private TextView date_size;
    private String search_code = "";//搜索的错误代码
    private String search_time = "";//搜索的时间
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fault_log);
        ac = (ApplicationClass) getApplication();// 初始化 ApplicationClass
        initialization();//初始化控件
        getJson();
    }

    //初始化控件
    private void initialization(){
        back = findViewById(R.id.fault_log_back);
        number = findViewById(R.id.fault_log_edit_text);
        date = findViewById(R.id.fault_log_text);
        recyclerView = findViewById(R.id.fault_log_recyclerview);
        clean = findViewById(R.id.fault_log_clean);
        search = findViewById(R.id.fault_log_edit_search);
        left = findViewById(R.id.fault_log_button_left);
        right = findViewById(R.id.fault_log_button_right);
        date_size = findViewById(R.id.fault_log_data_size);
        back.setOnClickListener(this);
        date.setOnClickListener(this);
        clean.setOnClickListener(this);
        search.setOnClickListener(this);
        left.setOnClickListener(this);
        right.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.fault_log_back){//点击返回按钮
            finish();
        } else if (v.getId() == R.id.fault_log_text) {//选择日期
            showCustomDatePickerDialog();
        } else if (v.getId() == R.id.fault_log_clean) {//点击清除按钮
            int ischeak = ac.DeleteSQLData_ErrorInfo();
            if (ischeak == 1){
                ToastUtils.show(this,"清除成功！");
                // 清空适配器数据
                errorDataList.clear();
                initOrRefreshRecyclerView(errorDataList);
            } else if (ischeak == 0) {
                ToastUtils.show(this,"清除失败！");
            }
        } else if (v.getId() == R.id.fault_log_edit_search) {//点击搜索按钮
            search_date();
        } else if (v.getId() == R.id.fault_log_button_left) {
            if (pageIndex > 1) {
                pageIndex--;
                getJson();
            }else {
                ToastUtils.show(this,"当前已经是第一页了");
            }
        } else if (v.getId() == R.id.fault_log_button_right) {
            if (pageIndex < pageCount) {
                pageIndex++;
                getJson();
            }else {
                ToastUtils.show(this,"当前已经是最后一页了");
            }
        }
    }

    //解析json数据
    public void getJson() {
        String json_data = ac.GetSQLData_ErrorInfo(search_code, search_time, String.valueOf(pageIndex), String.valueOf(limit));
        Log.d(TAG, "拿到的故障日志json数据： " + json_data);
        ac.SaveLog("拿到的故障日志json数据： " + json_data);
        try {
            JSONObject jsonObject = new JSONObject(json_data);
            success = jsonObject.getBoolean("success");
            pageIndex = jsonObject.getInt("page_index");
            pageCount = jsonObject.getInt("page_count");
            limit = jsonObject.getInt("limit");
            recordCount = jsonObject.getInt("record_count");
            dataSize = jsonObject.getInt("data_size");
            Log.d(TAG, "Success: " + success + " Page Index: " + pageIndex + " Page Count: " + pageCount + " Limit: "
                    + limit + " Record Count: " + recordCount + " Data Size: " + dataSize);

            JSONArray dataArray = jsonObject.getJSONArray("data");
            errorDataList.clear();
            for (int i = 0; i < dataArray.length(); i++) {
                ErrorData errorData = new ErrorData();
                JSONObject dataObject = dataArray.getJSONObject(i);
                errorData.setTimestamp(dataObject.optString("timestamp"));
                errorData.setErrorCode(dataObject.optString("error_code"));
                errorData.setErrorType(dataObject.optString("error_type"));
                errorData.setErrorDesc(dataObject.optString("error_desc"));
                errorData.setErrorTime(dataObject.optString("error_time"));
                errorDataList.add(errorData);
                Log.d(TAG, "Timestamp: " + errorData.getTimestamp() + " Error Code: " + errorData.getErrorCode() +
                        " Error Type: " + errorData.getErrorType() + " Error Desc: " + errorData.getErrorDesc() + " Error Time: " + errorData.getErrorTime());
            }
            // 确保UI更新在主线程中执行
            runOnUiThread(() -> {
                initOrRefreshRecyclerView(errorDataList);
                date_size.setText("第 " + pageIndex + " 页，共 " + pageCount + " 页");
            });
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d(TAG, "解析故障日志json数据失败，原因： " + e.getMessage());
            ac.SaveLog("解析故障日志json数据失败，原因： " + e.getMessage());
        }
    }

    // 初始化或者刷新adapter
    public void initOrRefreshRecyclerView(List<ErrorData> newData) {
        if (recyclerView.getAdapter() == null) {
            // 如果 RecyclerView 尚未初始化，则创建适配器并设置给 RecyclerView
            FaultLogAdapter adapter = new FaultLogAdapter(newData);
            recyclerView.setAdapter(adapter);
            // 设置布局管理器（如果尚未设置）
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
        } else {
            // 如果 RecyclerView 已经初始化，则获取适配器并更新数据
            FaultLogAdapter adapter = (FaultLogAdapter) recyclerView.getAdapter();
            if (adapter != null) {
                adapter.setData(newData); // 确保适配器中有setData方法来更新数据
                adapter.notifyDataSetChanged(); // 刷新整个列表
            }
        }
    }

    // 自定义日期选择弹窗代码示例
    private void showCustomDatePickerDialog() {
        final Dialog dialog = new Dialog(FaultLogActivity.this);
        dialog.setContentView(R.layout.custom_date_picker_dialog);

        CalendarView calendarView = dialog.findViewById(R.id.calenderView);
        Button btnCancel = dialog.findViewById(R.id.btn_cancel);
        Button btnConfirm = dialog.findViewById(R.id.btn_confirm);

        // 存储用户选择的日期
        final long[] selectedDateInMillis = new long[1];

        // 设置日期选择监听器
        calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
                // 将用户选择的日期存储起来
                Calendar calendar = Calendar.getInstance();
                calendar.set(year, month, dayOfMonth);
                selectedDateInMillis[0] = calendar.getTimeInMillis();
            }
        });

        // 设置取消按钮点击事件
        btnCancel.setOnClickListener(v -> dialog.dismiss());

        // 设置确定按钮点击事件
        btnConfirm.setOnClickListener(v -> {
            // 使用存储的日期
            if (selectedDateInMillis[0] != 0) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(selectedDateInMillis[0]);

                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，所以加1
                int day = calendar.get(Calendar.DAY_OF_MONTH);

                // 格式化日期字符串，确保月份和日期是两位数字
                String selectedDate = String.format("%d-%02d-%02d", year, month, day);
                Log.d(TAG, "Selected Date: " + selectedDate);
                date.setText(selectedDate);
            }
            dialog.dismiss();
        });

        dialog.show();

        // 设置弹窗大小
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
            layoutParams.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.8); // 设置宽度为屏幕宽度的80%
            layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT; // 高度自动调整
            dialog.getWindow().setAttributes(layoutParams);
        }
    }

    // 搜索图片搜索的方法
    private void search_date() {
        search_code = number.getText().toString();
        String time = date.getText().toString();
        Log.d(TAG, "Search Code: " + search_code + " Time: " + time);

        // 创建一个正则表达式，用于匹配'YYYY年MM月DD日'格式
        String regex = "^\\d{4}-\\d{2}-\\d{2}$"; // 确保月份和日期是两位数字
        if (time.matches(regex)) {
            // 如果匹配成功，执行相关逻辑，如搜索
            search_time = time;
            Log.d(TAG, "Search Time: " + search_time);
        } else {
            // 如果匹配失败，提示用户时间格式错误
            Log.d(TAG, "时间格式错误，请输入正确的YYYY年MM月DD日格式");
            search_time = "";
        }
        pageIndex = 1;
        Log.d(TAG, "Search Code: " + search_code + " Search Time: " + search_time);
        getJson();
    }


}